<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input-wrapper">
				<u-icon name="search" color="#909399" size="30"></u-icon>
				<input 
                    type="text" 
                    class="search-input" 
                    placeholder="请输入SN号" 
                    v-model="searchKeyword"
                    @confirm="handleSearch"
                    confirm-type="search"
                 />
			</view>
			<button class="search-button" @click="handleSearch">搜索</button>
		</view>

		<!-- SN 列表 -->
		<scroll-view scroll-y class="sn-list-scroll" @scrolltolower="loadMore">
            <!-- 加载提示 -->
             <view v-if="loading && !loadingMore" class="loading-placeholder">
                加载中...
            </view>
            <!-- 空列表提示 -->
			<view v-else-if="availableSNs.length === 0" class="empty-placeholder">
				暂无可用SN号
			</view>
            <!-- 列表项 -->
			<checkbox-group @change="checkboxChange" class="checkbox-group">
				<label class="sn-item" v-for="item in availableSNs" :key="item.sn">
					<checkbox 
                        class="sn-checkbox"
                        :value="item.sn" 
                        :checked="item.checked"
                     />
					 <view class="listitem-right">
					 	<view class="right-title disflex">
					 		<view class="disflex" @click="copy(item.sn)">
					 			<text>{{item.sn}}</text>
					 			<!-- <image src="/static/img/index/copy.png" mode="widthFix"
					 				style="width: 20px; height: 14px; margin-left: 5px;"></image> -->
					 		</view>
					 		<view class="right-title-right">
					 			￥{{item.fee || 0.00}}
					 		</view>
					 	</view>
					 	<view class="disflex right-concent">
					 		<view class="cptype" v-if="item.cp == '0'">电签</view>
					 		<view class="cptype" v-else>大POS</view>
					 
					 		<view class="Free">
					 			{{item.remarks || '服务费金额'}}
					 		</view>
					 	</view>
					 
					 </view>
					<!-- <text class="sn-number">{{ item.sn }}</text> -->
					<!-- 添加费用和备注信息 -->
                    <!-- <view class="sn-info">
                        <text class="sn-fee" v-if="item.fee">费用: {{item.fee}}元</text>
                        <text class="sn-remarks" v-if="item.remarks">备注: {{item.remarks}}</text>
                    </view> -->
				</label>
			</checkbox-group>
            
            <!-- 加载更多/无更多 -->
            <view class="load-more" v-if="availableSNs.length > 0">
                <text v-if="loadingMore">加载中...</text>
                <text v-else>没有更多了</text>
            </view>
		</scroll-view>

		<!-- 固定底部操作栏 -->
		<view class="footer-bar">
            <view class="footer-actions">
                <view class="selected-info">
                    已选{{selectedCount}}台
                </view>
                <view class="select-all-wrapper" @click="toggleSelectAll">
                    <checkbox :checked="isAllSelected" />
                    <text class="select-all-text">全选</text>
                </view>
            </view>
			<button class="confirm-button" @click="confirmSelection">确定</button>
		</view>
	</view>
</template>

<script>
const api = require('../../../config/api'); 
const util = require('../../../utils/util');

export default {
	data() {
		return {
            recordId: null, // 接收上个页面的记录ID
            batchNo: null, // 接收上个页面传来的订单批次号
            searchKeyword: '',
			availableSNs: [], // 从API获取的可选SN列表，包含选中状态 { sn: 'xxx', checked: false }
			initialSelectedSNs: [], // 从上个页面传来的已选SN
            selectedSNs: [], // 存储当前选中的SN数组，代替Map
            loading: true,
            pageNo: 1,       // 当前页码
            pageSize: 10,    // 每页数量
            totalPages: 1,   // 总页数
            totalItems: 0,   // 数据总量
            hasMore: true,   // 是否有更多数据
            loadingMore: false, // 是否正在加载更多
            loadingAllData: false // 是否正在加载所有数据
		};
	},
    computed: {
        selectedCount() {
            // 计算当前选中的SN数量
            return this.selectedSNs.length;
        },
        // 计算是否所有可用SN都被选中
        isAllSelected() {
            if (this.availableSNs.length === 0) return false;
            // 必须明确检查选中数量，防止误判
            if (this.selectedSNs.length !== this.availableSNs.length) return false;
            return this.availableSNs.every(item => this.selectedSNs.includes(item.sn));
        }
    },
	onLoad(options) {
        this.recordId = options.recordId || null;
        this.batchNo = options.batchNo || null;
        try {
            // 我们不再区分初始选中和用户选中的SN，统一处理
            const initialSelectedSNs = JSON.parse(options.selected || '[]');
            this.selectedSNs = [...initialSelectedSNs];
            this.initialSelectedSNs = []; // 不再使用这个字段
        } catch (e) {
            console.error('解析已选SN失败:', e);
            this.selectedSNs = [];
            this.initialSelectedSNs = [];
        }
        console.log('接收到的recordId:', this.recordId);
        console.log('接收到的batchNo:', this.batchNo);
        console.log('接收到的已选SNs:', this.selectedSNs);

        // 加载所有SN数据
        this.loadAllSNs();
	},
	methods: {
        // 加载所有SN列表
        async loadAllSNs() {
            try {
                this.loadingAllData = true;
                // 重置列表和页码
                this.pageNo = 1;
                this.hasMore = true;
                this.availableSNs = [];
                
                // 首次加载
                await this.fetchAvailableSNs(true);
                
                console.log('首次加载完成，是否还有更多:', this.hasMore);
                
                // 最多再加载5页，防止数据过多导致性能问题
                let pageCount = 0;
                while (this.hasMore && pageCount < 3) {
                    this.pageNo++;
                    pageCount++;
                    console.log('加载第', this.pageNo, '页');
                    await this.fetchAvailableSNs(false);
                }
                
                if (this.hasMore) {
                    console.log('由于数据量较大，已停止预加载，用户可通过滚动加载更多');
                }
            } catch (error) {
                console.error('加载所有SN列表失败:', error);
            } finally {
                this.loadingAllData = false;
                this.loading = false;
                this.loadingMore = false;
            }
        },
        
        // 加载更多
        loadMore() {
            console.log('触发加载更多', {
                loadingMore: this.loadingMore,
                hasMore: this.hasMore,
                loadingAllData: this.loadingAllData,
                currentPage: this.pageNo,
                totalPages: this.totalPages
            });
            
            if (this.loadingMore || !this.hasMore || this.loadingAllData) {
                console.log('跳过加载更多');
                return;
            }
            
            console.log('执行加载更多');
            this.loadingMore = true;
            this.pageNo++;
            this.fetchAvailableSNs(false);
        },
        
        // 获取可选SN列表
        async fetchAvailableSNs(reset = false) {
            if (reset) {
                this.loading = true;
                this.pageNo = 1;
            }
            
            try {
                // 准备请求参数
                const requestData = {
                    page: this.pageNo,
                    limit: this.pageSize,
                    sn: this.searchKeyword || ""
                };
                
                // 构建URL，拼接batchNo
                const apiUrl = this.batchNo ? 
                    api.terminalAllocationOrderList + '/' + this.batchNo : 
                    api.terminalAllocationOrderList;
                console.log('apiUrl:', apiUrl);
                
                // 调用新的API
                const res = await util.request(
                    apiUrl,
                    requestData,
                    'POST'
                );
                
                console.log('SN列表数据:', res);
                // 添加更详细的日志
                console.log('数据结构:', {
                    hasRows: !!res.data.rows,
                    hasRecords: !!res.data.records,
                    hasPages: !!res.data.pages,
                    hasPageSize: !!res.data.pageSize,
                    hasCurrent: !!res.data.current,
                    totalItems: res.data.total
                });
                
                if (res.code !== 0) {
                    uni.showToast({ title: res.msg || '加载失败', icon: 'none' });
                    return;
                }
                
                // 处理API返回数据
                const records = res.data.rows || [];
                
                // 更新总页数和数据总量
                const totalSize = res.data.total || 0;
                this.totalItems = totalSize;
                
                // 计算总页数
                const pageSize = this.pageSize;
                this.totalPages = Math.ceil(totalSize / pageSize);
                
                // 判断是否有更多数据
                this.hasMore = this.pageNo < this.totalPages;
                
                // 转换为需要的格式，并设置初始选中状态
                const newSNs = records.map(item => ({
                    sn: item.snNo, // SN号
                    id: item.id,    // 终端ID
					cp: item.cp,    // 终端ID
                    checked: this.selectedSNs.includes(item.snNo), // 根据当前选中状态设置
                    fee: item.fee,  // 费用信息
                    remarks: item.remarks  // 备注
                }));
                
                // 重置或追加数据
                if (reset) {
                    this.availableSNs = newSNs;
                } else {
                    this.availableSNs = [...this.availableSNs, ...newSNs];
                }
                
            } catch (error) {
                 console.error("加载SN列表失败:", error);
                 uni.showToast({ title: '网络错误', icon: 'none' });
                 
                 // 如果在自动加载过程中出错，抛出异常以中断循环
                 if (this.loadingAllData) {
                     throw error;
                 }
            } finally {
                if (!this.loadingAllData) {
                    this.loading = false;
                    this.loadingMore = false;
                }
            }
        },
        
        // 处理搜索
        handleSearch() {
            // 搜索时重新加载所有数据
            this.loadAllSNs();
        },

        // Checkbox 状态改变
		checkboxChange(e) {
            const selectedValues = e.detail.value; // value 是数组，包含所有选中的 checkbox 的 value
            console.log('选中的值数组:', selectedValues);
            
            // 更新选中状态
            this.selectedSNs = selectedValues;
            
            // 更新列表的 checked 状态
            this.availableSNs = this.availableSNs.map(item => ({
                ...item,
                checked: selectedValues.includes(item.sn)
            }));
            
            console.log('当前选中数量:', this.selectedSNs.length);
		},

        // 确定选择
        confirmSelection() {
            console.log('最终确定的SNs:', this.selectedSNs);
            // 触发事件，将选中的SN列表传回上一个页面
            uni.$emit('snSelected', { selectedSNs: this.selectedSNs });
            uni.navigateBack();
        },

        // 全选
        toggleSelectAll() {
            console.log('切换全选状态，当前状态:', this.isAllSelected);
            // 如果当前是全选状态，则取消所有选中
            if (this.isAllSelected) {
                // 清空选中状态
                this.selectedSNs = [];
                // 更新每项的checked状态
                this.availableSNs = this.availableSNs.map(item => ({
                    ...item,
                    checked: false
                }));
                console.log('已取消全选, 选中数量:', this.selectedSNs.length);
            } else {
                // 否则全选所有可用SN
                this.selectedSNs = this.availableSNs.map(item => item.sn);
                // 更新每项的checked状态
                this.availableSNs = this.availableSNs.map(item => ({
                    ...item,
                    checked: true
                }));
                console.log('已全部选中, 选中数量:', this.selectedSNs.length);
            }
        }
	}
};
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #fff;
}

/* --- 复用 SelectAlly 的搜索栏样式 --- */
.search-bar {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #fff; 
    border-bottom: 1rpx solid #f5f5f5;

	.search-input-wrapper {
		flex: 1;
		display: flex;
		align-items: center;
		background-color: #f5f5f5; 
		border-radius: 30rpx;
		padding: 10rpx 25rpx;
		margin-right: 20rpx;

		.search-input {
			flex: 1;
			font-size: 28rpx;
			margin-left: 10rpx;
            height: 40rpx; 
            line-height: 40rpx;
		}
	}

	.search-button {
		background-color: transparent; 
        color: #333; 
        border: none;
        padding: 0 10rpx; 
        margin: 0;
        font-size: 30rpx;
        height: 60rpx; 
        line-height: 60rpx;
        &::after {
            border: none;
        }
	}
}
/* --- 搜索栏样式结束 --- */

.sn-list-scroll {
    flex: 1; // 占据剩余空间
    height: 0; // 需要配合 flex: 1
    background-color: #fff;
}

.checkbox-group {
    // padding: 0 30rpx;
}

.sn-item {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 25rpx 30rpx;
    border-bottom: 1rpx solid #f5f5f5;

    &:last-child {
        border-bottom: none;
    }
    
    // 调整checkbox大小和边距
    .sn-checkbox {
        // transform: scale(0.8); // 缩小 checkbox
        margin-right: 20rpx;
    }
    // H5 和 App 端隐藏默认 checkbox 样式，用 ::before/::after 模拟
    // checkbox .wx-checkbox-input,
    // checkbox .uni-checkbox-input {
    //     width: 36rpx; 
    //     height: 36rpx;
    //     border-radius: 4rpx;
    // }
    // checkbox .wx-checkbox-input.wx-checkbox-input-checked::before,
    // checkbox .uni-checkbox-input.uni-checkbox-input-checked::before {
    //     font-size: 28rpx; 
    // }

    .sn-number {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        flex: 1;
        word-break: break-all; // 防止长 SN 溢出
    }
    
    .sn-info {
        width: 100%;
        padding-left: 60rpx; // 与checkbox对齐
        margin-top: 10rpx;
        display: flex;
        flex-direction: column;
        
        .sn-fee {
            font-size: 24rpx;
            color: #999;
        }
        
        .sn-remarks {
            font-size: 24rpx;
            color: #999;
            margin-top: 5rpx;
        }
    }
}

.loading-placeholder, .empty-placeholder {
	text-align: center;
	color: #999;
	font-size: 28rpx;
	padding: 80rpx 0;
}

/* --- 复用 ApproveExchange 的底部栏样式，稍作修改 --- */
.footer-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 20rpx 30rpx;
    box-sizing: border-box;

    .footer-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        margin-bottom: 15rpx;

        .selected-info {
            font-size: 28rpx;
            color: #6A9FFB;
        }

        .select-all-wrapper {
            display: flex;
            align-items: center;
            
            .select-all-text {
                font-size: 28rpx;
                color: #333;
                margin-left: 6rpx;
            }
        }
    }

    .confirm-button {
        background-color: #6A9FFB;
        color: #fff;
        border: none;
        border-radius: 40rpx;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 30rpx;
        width: 90%;
        align-self: center;
         &::after {
            border: none;
        }
    }
}

.load-more {
    text-align: center;
    padding: 20rpx 0 40rpx;
    color: #999;
    font-size: 26rpx;
}
.listitem-right {
		flex: 1;
		margin-right: 5px;
	}
	.right-title {
		margin-top: 5px;
		font-size: 16px;
		font-weight: 600;
		color: #000;
	}
	.disflex {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.cptype {
		color: #2F6DFE;
		padding: 5px 6px;
		border-radius: 20px;
		border: 1px solid #2F6DFE;
	}
</style> 